package milu;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.appengine.api.datastore.Blob;

class Box {
    public double leftX, topY, rightX, bottomY;  
    public Box(double leftX, double topY, double rightX, double bottomY) {
        this.leftX = leftX;
        this.topY = topY;
        this.rightX = rightX;
        this.bottomY = bottomY;
    }
}

public class ImageResizer {
    private Blob imageBin;

    public ImageResizer(Blob imageBin) {
        this.imageBin = imageBin;
    }
    private void moveLeft(double left, Box box) {
        box.leftX += left;
        box.rightX += left;
    }
    private void moveTop(double top, Box box) {
        box.topY += top;
        box.bottomY += top;
    }

    public Blob resize(String width, String height) throws java.lang.IllegalArgumentException {
        byte[] imageBytes = imageBin.getBytes();

        // Divide the width you want to crop to by the width of the image; likewise for height. 
        // This will give you the percentages (values between 0 and 1) you need to pass to the Images API.
        double dwidth = Double.parseDouble(width), dheight = Double.parseDouble(height);
        double iwidth = Integer.parseInt(width), iheight = Integer.parseInt(height);

        ImagesService imagesService = ImagesServiceFactory.getImagesService();
        Image currImage = ImagesServiceFactory.makeImage(imageBytes);

        // resize to width from parameters + 100 - just some padding
        Transform resize = ImagesServiceFactory.makeResize(Integer.parseInt(width)+100, Integer.parseInt(height)+100);
        currImage = imagesService.applyTransform(resize, currImage);

        int currWidth = currImage.getWidth(), currHeight = currImage.getHeight();

        double wPerc = dwidth / currWidth,
               hPerc = dheight / currHeight;

        double boxWidthHalph = (iwidth/2) / currWidth;
        double boxHeightHalph = (iheight/2) / currHeight;

        Box box = new Box(0.0, 0.0, wPerc, hPerc);
        // move it to the center
        moveLeft(0.50 - boxWidthHalph, box);
        moveTop(0.50 - boxHeightHalph, box);

        // crop might fail if values are out-of-bounds
        if(box.leftX >= 0 && box.topY >= 0 && box.rightX >= 0 && box.bottomY >= 0) {
            Transform crop = ImagesServiceFactory.makeCrop(box.leftX, box.topY, box.rightX, box.bottomY);
            currImage = imagesService.applyTransform(crop, currImage);
        }

        imageBytes = currImage.getImageData();

        return new Blob(imageBytes);
    }
}
